<template>
<div>
<!--搜索区域-->
<el-card class="search-card">
  <!--搜索表单
    ref是表单的引用名称，用于表单校验和表单重置，需要这个名字
    rules是表单校验规则
    model是表单数据模型，用于绑定表单数据
  -->
  <el-form ref="searchUser" size="small " :inline="true" :model="searchUser" label-width="80px">
    <!--prop是表单校验和重置需要的绑定变量名,且这个名字和绑定变量名一致-->
    <el-form-item label="用户名" prop="username">
      <el-input v-model="searchUser.username" style="width: 100px"></el-input>
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="searchUser.phone" show-password style="width: 100px"></el-input>
    </el-form-item>
    <el-form-item label="注册时间" prop="searchTime">
      <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="searchUser.searchTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
      </el-date-picker>
    </el-form-item>
    <el-form-item>
      <el-button size="mini" type="primary" @click="onSearch">搜索</el-button>
      <!--@click是点击事件，resetForm是重置方法，searchUser是表单引用名称-->
      <el-button size="mini" @click="resetForm('searchUser')">重置</el-button>
    </el-form-item>
  </el-form>
</el-card>
  <!--表格区域-->
<el-card class="table-card">
  <!--批量删除-->
  <el-button size="mini" type="warning" @click="handleDeleteAll">批量删除</el-button>
  <!--添加-->
  <el-button size="mini" type="primary" @click="openadd">添加</el-button>
  <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%">
    <el-table-column
        type="selection"
        width="55">
    </el-table-column>
    <el-table-column
        prop="id"
        label="ID"
        width="90">
    </el-table-column>
    <el-table-column
        prop="username"
        label="用户名"
        width="100">
    </el-table-column>
    <el-table-column
        prop="password"
        label="密码"
        width="100">
    </el-table-column>
    <el-table-column
        prop="phone"
        label="手机号" width="120%">
    </el-table-column>
    <el-table-column
        prop="createTime"
        value-format="yyyy-MM-dd"
        label="注册时间" width="120%">
    </el-table-column>
    <el-table-column
        prop="money"
        label="余额" width="100%">
    </el-table-column>
    <el-table-column
        prop="sex"
        label="性别" width="100%">
      <template slot-scope="scope">
        <el-tag
            :type="scope.row.sex == '1' ? 'primary' : 'success'"
            disable-transitions>{{scope.row.sex==1 ? '男' : '女'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作">
<!--      删除按钮-->
      <template slot-scope="scope">
        <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        <el-button
            size="mini"
            type="primary"
            @click="handleUpdate('修改用户',scope.$index,scope.row)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--分页区域-->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[3, 6, 10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
  </el-pagination>
</el-card>
  <!--添加用户对话框-->
  <el-dialog :title="dialogName" :visible.sync="dialogVisible" width="30%" height="50px">
    <el-form ref="addUser" :rules="rules" size="small " :inline="true" :model="addUser" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addUser.username" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addUser.password" show-password style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="addUser.phone" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="addUser.sex">
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="余额" prop="money">
        <el-input v-model="addUser.money" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" @click="submitForm('addUser')">确定</el-button>
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</div>
</template>

<script>
import axios from "axios";

export default {
  name: "",
  data() {
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'));
        }
        callback();
      }
    };
    var validateMoney = (rule, value, callback) => {
      // 校验余额是否为数字,isNaN是js的内置函数,判断是否为数字 not a number
      if (isNaN(value)) {
        callback(new Error('要求输入数字!'));
      }
      callback();
    }
    return {
      searchUser: {
        username: '',
        phone: '',
        searchTime:'',
        beginTime:'',
        endTime:''
      },
      tableData: [
        {
          username:'',
          password:'',
          phone:'',
          createTime:'',
          money:'',
          sex:''
        }
      ],
      total:null,
      pageSize:3,
      pageNum:1,
      idlist:[],
      //添加用户弹窗
      dialogVisible:false,
      addUser:{
        username:'',
        password:'',
        phone:'',
        //createTime:'',
        money:'',
        sex:''
      },
      //表单校验规则
      rules:{
        username:[
          {required:true,message:'请输入用户名',trigger:'blur'},
          {min:3,max:5,message:'长度在3-5个字符',trigger:'blur'}
        ],
        password:[
          {required:true,message:'请输入密码',trigger:'blur'},
          {min:3,max:5,message:'长度在3-5个字符',trigger:'blur'}
        ],
        phone:[{validator:validatePhone,trigger:'blur'}],
        money:[{validator:validateMoney,trigger:'blur'}],
        sex:[
          { required:true,message:'请选择性别',trigger:'blur'},
        ]

      },
      dialogName:'添加用户',
    }
  },
  created(){
    this.fetchData()
  },
  methods: {
    //查询列表数据
    fetchData(){
      console.log(this.searchUser)
      //v1正常查询
      // axios.get("/user/list")
      //     .then(res=>{
      //       console.log(res.data)
      //       this.tableData=res.data;
      //     })
      //v2分页查询
      // axios.get("/user/list",{
      //   params:{
      //   pageNum:this.pageNum,
      //   pageSize:this.pageSize
      // }
      // })
      //模糊查询
      axios.get("/user/list",{
        params:{
          username:this.searchUser.username,
          phone:this.searchUser.phone,
          beginTime:this.searchUser.beginTime,
          endTime:this.searchUser.endTime,
          pageNum:this.pageNum,
          pageSize:this.pageSize
        }
      })
      .then(res=>{
        //点击确定
        if(res.code=='40003'){
          this.$confirm('用户登录超时，请重新登录', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //超时了重新登陆应该设置令牌为空
            this.$store.commit('setToken','')
            this.$router.push("/")
          }).catch(err=>{
            console.log(err)
          })

        }else{
          //console.log(res.data)
          this.tableData=res.data.list;
          this.total=res.data.total
        }
      }).catch(err=>{
        console.log(err)
      })

    },
    //搜索
    onSearch(){
      //console.log(this.searchUser)
      this.searchUser.beginTime = this.searchUser.searchTime[0]
      this.searchUser.endTime = this.searchUser.searchTime[1]
      console.log(this.searchUser)
      this.fetchData();
    },
    //重置
    resetForm(searchUser) {
      this.$refs[searchUser].resetFields();
      this.searchUser.searchTime='';
      this.searchUser.username='';
      this.searchUser.phone='';
      this.searchUser.beginTime='';
      this.searchUser.endTime='';
      this.pageNum=1;
      this.pageSize=3;
      this.fetchData();
    },
    //分页大小改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize=val;
      this.pageNum=1;
      //大小改变重新查询
      this.fetchData();
    },
    //分页页码改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val;
      //页码改变重新查询
      this.fetchData();
    },
    //删除单条
    handleDelete(index, row){
      this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get("/user/delete?id="+row.id)
            .then(res=>{
              this.pageNum=1;
              this.fetchData();
            }).catch(err=>{
          console.log(err)
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //删除多条数据
    handleDeleteAll(index, row){
      this.$confirm('是否删除用户'+this.idlist, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //发送请求
        axios.get("/user/deleteAll?id="+this.idlist)
            .then(res=>{
              console.log(res.data)
              if(res.code==2000){
                this.$message.success("删除成功");
                this.pageNum=1;
                this.fetchData();
              }
            }).catch(err=>{
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

},
    //复选框改变
    handleSelectionChange(val){
      // 每次改变要清空数组
      this.idlist=[];
      val.forEach(item=>{
        this.idlist.push(item.id)
      })
      console.log(this.idlist)
    },
    //添加和修改用户
    submitForm(addUser){
      //console.log(this.addUser)
      //既做添加操作又做修改操作
      this.$refs[addUser].validate(valid => {
        if(valid){
          if(this.dialogName=="添加用户"){
            console.log(this.addUser)
            axios.post("/user/add",this.addUser)
                .then(res=>{
                  //console.log(res.data)
                  if(res.code==2000){
                    //添加成功刷新
                    this.pageNum=1;
                    this.fetchData()
                    this.$message({
                      message:"添加成功",
                      type:"success"
                    })
                  }
                }).catch(err=>{
              console.log(err)
            })
            //提交成功后关闭对话框
            this.dialogVisible=false;
            this.addUser.phone='',
                this.addUser.username='',
                this.addUser.password='',
                this.addUser.sex='',
                this.addUser.money=''
          }else if(this.dialogName=="修改用户"){
            console.log(this.addUser)
            axios.post("/user/update",this.addUser)
                .then(res=>{
                  if(res.code==2000){
                    //修改成功刷新
                    this.pageNum=1;
                    this.fetchData()
                    this.$message.success("修改成功")
                  }
                }).catch(err=>{
              console.log(err);
            })
            this.dialogVisible=false;
          }
        }else{
          return false;
        }
      })
    },
    //修改弹出表单框
    handleUpdate(dialogName,index,row){
      this.dialogName=dialogName;
      this.dialogVisible=true;
      this.addUser=row;
      // 确保性别值是字符串类型，与radio的label匹配
      this.addUser.sex = String(this.addUser.sex);
      //console.log(index,row)
    },
    //添加按钮
    openadd(){
      this.addUser={
        username:"",
        password:"",
        phone:"",
        money:"",
        sex:""
      }
      this.dialogVisible=true;
      this.dialogName="添加用户"
    }
  }
}
</script>

<!-- 添加非 scoped 样式来覆盖 Element UI 默认样式 -->
<style>
.search-card {
  width: 100%;
  height: 70px;
  margin-top: 1px;
}
.table-card{
  width: 100%;
  height: 450px;
  margin-top: 4px;
}
/* 深色表头样式 */
.el-table .el-table__header-wrapper th {
  background-color: #f8f8f9 !important; /* Element UI 主题色 */
  color: black;
}
</style>